/**
 * Created by Administrator on 2017/7/4.
 */
var config = require('../../config.json');
var passport = require('passport');
var gitHubStrategy = require('passport-github2').Strategy;
var User = require('../models/user');

passport.serializeUser(function (user, done) {
  done(null, user);
});

passport.deserializeUser(function (obj, done) {
  done(null, obj);
});

passport.use(new gitHubStrategy({
    clientID: config.githubAuth.clientId,
    clientSecret: config.githubAuth.clientSecret,
    callbackURL: config.githubAuth.callbackUrl
  },
  function (accessToken, refreshToken, profile, done) {
    process.nextTick(function () {
      //先查询用户是否存在
      User.findOne({name: profile.username}, function (err, _user) {
        if (_user) return done(null, _user);
        var newUser = new User({
          name: profile.username,
          password: profile.username,
          role: 0,
          time: Date.now()
        });
        newUser.save(function (err, _new) {
          return done(null, _new);
        });
      });
    });
  }
));

module.exports = passport;